package cn.itcast.controller;

import cn.itcast.domain.Area;
import cn.itcast.service.AreaService;
import cn.itcast.utils.DownLoadUtils;
import cn.itcast.utils.PinYin4jUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Controller
public class AreaController {

    @Autowired
    private AreaService areaService;

    @RequestMapping("/area_batchImport")
    @ResponseBody
    public String batchImport(MultipartFile file) {
        ArrayList<Area> areas = new ArrayList<>();
        InputStream inputStream =null;
        try {
            inputStream = file.getInputStream();
            HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
            HSSFSheet sheetAt = workbook.getSheetAt(0);
            for (Row row : sheetAt) {
                //跳过第一行
                if (row.getRowNum()==0 ) {
                    continue;
                }
                Cell cell = row.getCell(0);
                if (cell==null|| StringUtils.isBlank(cell.getStringCellValue())){
                    continue;
                }
                Area area = new Area();
                area.setId(row.getCell(0).getStringCellValue());
                area.setProvince(row.getCell(1).getStringCellValue());
                area.setCity(row.getCell(2).getStringCellValue());
                area.setDistrict(row.getCell(3).getStringCellValue());
                area.setPostcode(row.getCell(4).getStringCellValue());
                //城市编码,简码设置
                areas.add(addCode(area));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        areaService.saveAll(areas);
        return "ok";

    }

    @RequestMapping("/area_save")
    @ResponseBody
    public Map save(Area area){
        HashMap map = new HashMap();
        String id = area.getId();
        Area area1 = areaService.findById(id);
        System.out.println(area1);
        if (area1!=null) {
            map.put("flag",false);
            map.put("message","主键重复,添加失败");
            return map;
        }
        areaService.save(addCode(area));
        map.put("flag",true);
        map.put("message","添加成功");
        return map;
    }

    @RequestMapping("/area_edit")
    @ResponseBody
    public String edit(Area area){
        areaService.save(addCode(area));
        return "ok";
    }

    @RequestMapping("/area_pageQuery")
    @ResponseBody
    public Map pageQuery(Area area,int page, int rows){
        //System.out.println(page+"   "+rows);
        HashMap map = new HashMap();
        Page<Area> pageQuery = areaService.pageQuery(area,page, rows);
        map.put("total",pageQuery.getTotalElements());
        map.put("rows",pageQuery.getContent());
        return map;
    }

    @RequestMapping("/area_delete")
    public String restore(@RequestParam(value = "ids")String ids){
        //System.out.println("ids = " + ids);
        String[] idArr = ids.split(",");
        List<String> list = Arrays.asList(idArr);
        areaService.delete(list);
        return "redirect:/pages/base/area.html";
    }



    /**
     *添加编码
     * @param area
     * @return
     */
    public Area addCode(Area area){
        //城市编码
        String citycode = PinYin4jUtils.hanziToPinyin(area.getCity().replace("市", ""), "");
        area.setCitycode(citycode);
        //简码
        StringBuilder stringBuilder = new StringBuilder(area.getProvince());
        String shortCodeStr = stringBuilder.append(area.getCity()).append(area.getDistrict()).toString();
        String[] codeArr = PinYin4jUtils.getHeadByString(shortCodeStr.replace("市", ""));
        StringBuilder stringBuilder1 = new StringBuilder();
        for (String code : codeArr) {
            stringBuilder1.append(code);
        }
        area.setShortcode(stringBuilder1.toString());
        return area;

    }


    @RequestMapping("/area_export")
    @ResponseBody
    public String export(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("Sheet1");
        HSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("区域编号");
        row.createCell(1).setCellValue("省份");
        row.createCell(2).setCellValue("城市");
        row.createCell(3).setCellValue("区域");
        row.createCell(4).setCellValue("邮编");
        List<Area> areaList = areaService.findAll();
        for (int i = 1; i <= areaList.size(); i++) {
            HSSFRow sheetRow = sheet.createRow(i);
            Area area = areaList.get(i - 1);
            sheetRow.createCell(0).setCellValue(area.getId());
            sheetRow.createCell(1).setCellValue(area.getProvince());
            sheetRow.createCell(2).setCellValue(area.getCity());
            sheetRow.createCell(3).setCellValue(area.getDistrict());
            sheetRow.createCell(4).setCellValue(area.getPostcode());
        }

        //获得浏览器代理信息
        String userAgent = request.getHeader("USER-AGENT");
        String finalFileName ="地域.xls";
        finalFileName = DownLoadUtils.getFileName(userAgent, finalFileName);

        //设置HTTP响应头
        response.reset();//重置 响应头
        response.setContentType("application/vnd.ms-excel");//告知浏览器下载文件，而不是直接打开，浏览器默认为打开
        response.addHeader("Content-Disposition", "attachment;filename=\"" + finalFileName + "\"");//下载文件的名称
        ServletOutputStream os = response.getOutputStream();
        workbook.write(os);
        os.close();
        return "ok";


    }




}
